/*
 * #%L
 * SwiftUIWeb Maven Webapp
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
/**
 * 
 */
package com.linkwithweb.products.swiftui.controller;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.linkwithweb.products.swiftui.context.SystemContext;
import com.linkwithweb.products.swiftui.dataobject.FrameworkBackup;
import com.linkwithweb.products.swiftui.dataobject.FrameworkUpload;
import com.linkwithweb.products.swiftui.dataobject.FrameworkUser;
import com.linkwithweb.products.swiftui.utils.JCryptionUtil;

/**
 * @author ashwin kumar
 * 
 */
@Controller
public class FrameworkManagementHandler extends AbstractController {
	private static final transient Log logger = LogFactory.getLog(FrameworkManagementHandler.class);

	/**
	 * @param request
	 * @param response
	 */
	@RequestMapping("/securityHandler")
	@ResponseBody
	public String getKeys(HttpServletRequest request, HttpServletResponse response) {

		if (request.getParameter("generateKeypair") != null) {

			KeyPair keys = SystemContext.getInstance().getKeys();

			request.getSession().setAttribute("keys", keys);

			StringBuffer output = new StringBuffer();

			String e = JCryptionUtil.getPublicKeyExponent(keys);
			String n = JCryptionUtil.getPublicKeyModulus(keys);
			String md = String.valueOf(JCryptionUtil.getMaxDigits(512));

			output.append("{\"e\":\"");
			output.append(e);
			output.append("\",\"n\":\"");
			output.append(n);
			output.append("\",\"maxdigits\":\"");
			output.append(md);
			output.append("\"}");

			output.toString();
			return output.toString().replaceAll("\r", "").replaceAll("\n", "").trim();
		} else {
			String mediUser = request.getParameter("mediUser");
			String mediPassword = request.getParameter("mediPass");
			String clientIdentifier = request.getParameter("identifier");
			FrameworkUser user = getPlatformService().loadUser(mediUser, mediPassword);
			if (user == null) {
				return "false";
			} else {
				return "true";
			}
		}

	}

	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/generateReports")
	@ResponseBody
	public String generateReports(HttpServletRequest request, HttpServletResponse response) {
		getPlatformService().connectAndGenerateReports(null);
		return "success";

	}

	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/canRefreshTable")
	@ResponseBody
	public String canRefreshTable(HttpServletRequest request, HttpServletResponse response) {
		String tableName = request.getParameter("tableName");
		String returnString = SystemContext.getInstance().getRefreshTableMap().get(tableName) == null ? "false"
				: SystemContext.getInstance().getRefreshTableMap().get(tableName).toString();
		if (!StringUtils.equalsIgnoreCase(returnString, "false")) {
			SystemContext.getInstance().getRefreshTableMap().put(tableName, null);
		}

		return returnString;
	}

	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/executeScript")
	@ResponseBody
	public String executeSript(HttpServletRequest request, HttpServletResponse response) {
		try {
			String sqlScript = request.getParameter("sqlScript");

			getPlatformService().update(sqlScript, "jdbcTemplate", new Object[] {});
		} catch (Exception e) {
			logger.debug("Error while executing script", e);
			SystemContext.getInstance().getMessages().add(e.getLocalizedMessage());
			return e.getLocalizedMessage();
		}
		return "Successfuly Executed";
	}
	
	
	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/executeScriptFile")
	@ResponseBody
	public String executeSriptFile(HttpServletRequest request, HttpServletResponse response) {
		try {
			String sqlScript = request.getParameter("sqlScript");

			getPlatformService().update(sqlScript, "jdbcTemplate", new Object[] {});
		} catch (Exception e) {
			logger.debug("Error while executing script", e);
			SystemContext.getInstance().getMessages().add(e.getLocalizedMessage());
			return e.getLocalizedMessage();
		}
		return "Successfuly Executed";
	}

	/**
	 * @param fileName
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/export/{fileName}", method = RequestMethod.GET)
	public void exportReport(@PathVariable("fileName") String fileName, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls\"");
			response.setContentType("application/octet-stream");
			// response.setContentType("text/plain");

			getPlatformService().generateReport(fileName, null, null, response.getOutputStream());

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	
	@RequestMapping(value = "/files/{fileType}", method = RequestMethod.GET)
	public ModelAndView getFiles(@PathVariable("fileType") String fileType, HttpServletRequest request,
			HttpServletResponse response) {
		List<FrameworkUpload> fileUploads = getPlatformService().getFilesByTag(fileType); 
		
		Map paramMap = new HashMap();
		paramMap.put("filesList", fileUploads);

		return new ModelAndView("management/fileList", paramMap);
	}
	

	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/v1/backups/backupDB")
	@ResponseBody
	public String backupDB(HttpServletRequest request, HttpServletResponse response) {
		getPlatformService().saveBackupDetails(new FrameworkBackup());
		return "success";

	}
	
	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/v1/backups/list", method = RequestMethod.GET)
	public ModelAndView getBackups(HttpServletRequest request,
			HttpServletResponse response) {
		List<FrameworkBackup> backups = getPlatformService().loadBackups(); 
		
		Map paramMap = new HashMap();
		paramMap.put("backupList", backups);

		return new ModelAndView("management/backupList", paramMap);
	}

	
}
